
$(function(){

    // Accordion
    $("div#container-exportarxml").wijaccordion({
        requireOpenedPane: false,
        animated: "animate"
    });
    $("div#container-exportarxml").wijaccordion("activate", 1);

    $('.date').live('click', function() {
        $(this).datepicker('destroy').datepicker({
            showOn:'focus', 
            changeMonth: true,
	    changeYear: true
        }).focus();
    });

    $('#div-<?php echo $this->pre ?>-4').dialog({
	autoOpen :false,
	modal    :true ,
	resizable:false,
	width    :500
    });

    //$("#borrar,#importar,#generarxml").button();
    $("#borrar").button({ icons:{primary:"ui-icon-trash"} });
    $("#importar").button({ icons:{primary:"ui-icon-extlink"} });
    $("#generarxml").button({ icons:{primary:"ui-icon-document"} })
        .click(function(){ 
            $.post("<?php echo site_url($this->url.'optionsForSelect')?>", {}, function(options){
                $("#anomesenvio").html(options);
            });
            $( "#dialog-form-genxml" ).wijdialog( "open" ); 
        });

    allFields = $( [] ).add($("#anomesenvio"));

    //Dialog que se muestra cuando es "clickeado" el boton "Generar XML".
    $('#dialog-form-genxml').wijdialog({
        autoOpen: false,
        captionButtons: {
            refresh: { visible: false }
        },
        modal:true,
        buttons: {
            "Generar": function(){
                var bValid = true;
                allFields.removeClass( "ui-state-error" );
                bValid = bValid && check($("#anomesenvio"), "Debe seleccionar el año y mes de envío");
                if ( bValid ) {
                    window.open('<?php echo site_url("reportes/exportarxml/generar") ?>/'+ $("#anomesenvio").val(),'XML Generado desde el portal de empleo', 'width=300,  height=300, scrollbars=Yes, status=Yes, resizable=Yes,  screenx=5,  screeny=5'  );						
                    $( this ).dialog( "close" );
                }  
            },
            "Cancelar": function(){
                $(this).wijdialog("close");
            }
        },
        close:    function(){ allFields.val("").removeClass("ui-state-error"); },
        open:     function(){ $(".validateTips").text("Seleccione el año y mes de envío");	}
    });
    
    $("#enviar").button({ icons:{primary:"ui-icon-transferthick-e-w"} });
    $("#reset").button({ icons:{primary:"ui-icon-refresh"} });

    // $('#borrar').click(function(){
    //     hace_post('<?php echo site_url($this->url."borrar") ?>',false,false);
    //     jQuery("#filtro-<?php echo $this->pre ?>").trigger("reloadGrid");
    //     jQuery("#filtro-<?php echo $this->pret ?>").trigger("reloadGrid");
    // });

    // $('#importar').click(function(){
    //     data='mes='+$('#div-<?php echo $this->pre ?>-4 #mes').val();
    //     $('#div-<?php echo $this->pre ?>-4').dialog({
    //         buttons: {
    //     	"Importar Datos del portal de empleo": function() {
    //     	    hace_post('<?php echo site_url($this->url."importar") ?>',data,false);
    //     	    jQuery("#filtro-<?php echo $this->pre ?>").trigger("reloadGrid");
    //     	    jQuery("#filtro-<?php echo $this->pret ?>").trigger("reloadGrid");
    //     	    $( this ).dialog( "close" );
    //     	},
    //     	Cancelar: function() {
    //     	    $( this ).dialog( "close" );
    //     	}
    //         }
    //     });
    //     $('#div-<?php echo $this->pre ?>-4').dialog('open');
    // });

    // $('#generarxml').click(function(){
    //     window.open('<?php echo site_url("reportes/exportarxml/generar") ?>','borrar', 'width=300,  height=300, scrollbars=Yes, status=Yes, resizable=Yes,  screenx=5,  screeny=5'  );
    // });


    function dialogo(rowsSelected){
	if(rowsSelected=='_'){
	    accion='add';
	}else{
	    //window.console.log(a);
	    if(jQuery.type(rowsSelected)=='array'){
		cantidad=rowsSelected.length;
		if(cantidad>1){
		    htmlForm='<?php echo $this->lang->line("MSJ_ERROR_DOBLE_EDITAR") ?>';
		    htmlDialog = "<div id='" + "filtro-<?php echo $this->pre ?>-double" + "'  >" + htmlForm + "</div>";
		    $("body").append(htmlDialog);

		    $("#"+"filtro-<?php echo $this->pre ?>-double" ).dialog({
			height: 140,
			modal: true
			//,
			//beforeClose: function(event, ui) {
			//	$("#"+"filtro-<?php echo $this->pre ?>-double" ).dialog("destroy");
			//}
		    });
		    return false;
		}else{
		    accion='edit';
		}
	    }else{
		accion='edit';
	    }
	}

	var bodyForm    = $('form', 'div#dialog-form-add').html();
	var propiedades={
	    width : 700,
	    height: 500,
	    show  : 'scale',
	    hide  : 'scale',
	    collapsingAnimation:
	    {
		animated: "clip",
		duration: 300,
		easing: "easeOutExpo"
	    },
	    expandingAnimation: {
		animated: "clip",
		duration: 300,
		easing: "easeOutExpo"
	    }
	};

	//window.console.log(rowsSelected);
	//window.console.log(a);
        
	idDialog = $("table#filtro-<?php echo $this->pre ?>").jqGrid('getDialogsForms', accion, rowsSelected, bodyForm, "<?php echo $this->lang->line('FORM_ADD_TITLE') ?>",propiedades);
        $('.validateTips').text("");
	//$('div#'+idDialog+' #nacimiento').datepicker({ dateFormat: 'dd/mm/yy' });
	//$('div#'+idDialog+' #fcolocado').datepicker({ dateFormat: 'dd/mm/yy' });
	$('#'+idDialog+' #tabs-<?php echo $this->pre ?>'+' #div-<?php echo $this->pre ?>-2'+' #table-<?php echo $this->pre ?>-2'+' #fregistro').datepicker({ dateFormat: 'dd/mm/yy' });

	$('div#'+idDialog+'  #tabs-<?php echo $this->pre ?>').tabs();

	if(accion=='edit'){
	    rowData=$("table#filtro-<?php echo $this->pre ?>").jqGrid('getRowData',rowsSelected);
	    $('[id="'+idDialog+'"] [name="discapacidad"]'    ).prop("selectedIndex",rowData.o_discapacidad);
	    $('[id="'+idDialog+'"] [name="inmigrante"]'      ).prop("selectedIndex",rowData.o_inmigrante);
	    $('[id="'+idDialog+'"] [name="colocado"]'        ).prop("selectedIndex",rowData.o_colocado);
	    $('[id="'+idDialog+'"] [name="sexo"]'            ).prop("selectedIndex",rowData.o_sexo);
	    $('[id="'+idDialog+'"] [name="tcontrato"]'       ).prop("selectedIndex",rowData.o_tcontrato);
	    $('[id="'+idDialog+'"] [name="nivelformativo"]'  ).prop("selectedIndex",rowData.o_nivelformativo);
	    window.console.log(rowData);
	}
    }

    jQuery("#filtro-<?php echo $this->pre ?>").jqGrid({
	url:'<?php echo site_url($this->url.'grid') ?>',
	datatype: "json",
        colNames:[
            "<?php echo $this->lang->line('G_ID')                            ?>",
	    "<?php echo $this->lang->line('G_EMPRESA_ID')                    ?>",
	    "<?php echo $this->lang->line('G_DNI')                           ?>",
	    "<?php echo $this->lang->line('G_APELLIDO1')                     ?>",
	    "<?php echo $this->lang->line('G_APELLIDO2')                     ?>",
	    "<?php echo $this->lang->line('G_NOMBRE')                        ?>",
	    "<?php echo $this->lang->line('G_NACIMIENTO')                    ?>",
	    "<?php echo $this->lang->line('G_SEXO')                          ?>",
	    "<?php echo $this->lang->line('G_NIVELFORMATIVO')                ?>",
	    "<?php echo $this->lang->line('G_DISCAPACIDAD')                  ?>",
	    "<?php echo $this->lang->line('G_INMIGRANTE')                    ?>",
	    "<?php echo $this->lang->line('G_COLOCADO')                      ?>",
	    "<?php echo $this->lang->line('G_FCOLOCADO')                     ?>",
	    "<?php echo $this->lang->line('G_TCONTRATO')                     ?>",
	    "<?php echo $this->lang->line('G_CIFNIF')                        ?>",
	    "<?php echo $this->lang->line('G_EMPRESA')                       ?>",
	    "<?php echo $this->lang->line('G_ANO_MES_ENVIO')                 ?>",
	    ""                                                                  ,
	    ""                                                                  ,
	    ""                                                                  ,
	    ""                                                                  ,
	    ""                                                                  ,
            ""                                                                  ,
        ],
	colModel:[
	    {
		name          :'id'                     ,
		index         :'id'                     ,
		width         :20                       ,
		key           :true                     ,
		hidden        :true                     ,
	    },
	    {
		name          :'empresa_id'             ,
		index         :'empresa_id'             ,
		width         :25                       ,
		hidden        :true                     ,
	    },
	    {
		name          :'dni'                    ,
		index         :'dni'                    ,
		width         :20                       ,
	    },
	    {
		name          :'apellido1'              ,
		index         :'apellido1'              ,
		width         :20                       ,
	    },
	    {
		name          :'apellido2'              ,
		index         :'apellido2'              ,
		width         :20                       ,
		hidden        :true                     ,
	    },
	    {
		name          :'nombre'                 ,
		index         :'nombre'                 ,
		width         :20                       ,
	    },
	    {
		name          :'nacimiento'             ,
		index         :'nacimiento'             ,
		width         :25                       ,
		hidden        :true                     ,
	    },
	    {
		name          :'sexo'                   ,
		index         :'sexo'                   ,
		width         :30                       ,
		hidden        :true                     ,

	    },
	    {
		name          :'nivelformativo'         ,
		index         :'nivelformativo'         ,
		width         :30                       ,
	    },
	    {
		name          :'discapacidad'           ,
		index         :'discapacidad'           ,
		width         :25                       ,
	    },
	    {
		name          :'inmigrante'             ,
		index         :'inmigrante'             ,
		width         :20                       ,
	    },
	    {
		name          :'colocado'               ,
		index         :'colocado'               ,
		width         :20                       ,
	    },
	    {
		name          :'fcolocado'              ,
		index         :'fcolocado'              ,
		width         :25                       ,
	    },
	    {
		name          :'tcontrato'              ,
		index         :'tcontrato'              ,
		width         :20                       ,
	    },
	    {
		name          :'cifnif'                 ,
		index         :'cifnif'                 ,
		width         :20                       ,
	    },
	    {
		name          :'empresa'                ,
		index         :'empresa'                ,
		width         :25                       ,
	    },
	    {
		name          :'o_discapacidad'         ,
		index         :'o_discapacidad'         ,
		hidden        :true                     ,
	    },
	    {
		name          :'o_inmigrante'           ,
		index         :'o_inmigrante'           ,
		hidden        :true                     ,
	    },
	    {
		name          :'o_colocado'             ,
		index         :'o_colocado'             ,
		hidden        :true                     ,
	    },
	    {
		name          :'o_sexo'                 ,
		index         :'o_sexo'                 ,
		hidden        :true                     ,
	    },
	    {
		name          :'o_nivelformativo'       ,
		index         :'o_nivelformativo'       ,
		hidden        :true                     ,
	    },
	    {
		name          :'o_tcontrato'            ,
		index         :'o_tcontrato'            ,
		hidden        :true                     ,
	    },
            {
		name          :'ano_mes_envio'          ,
		index         :'ano_mes_envio'          
	    }
	],
	rowNum       : 10,
	width        : 900,
	height       : "auto",
	rowList      : [10,20,30],
	pager        : '#barra-<?php echo $this->pre ?>',
	sortname     : 'dni',
	viewrecords  : true,
	sortorder    : "asc",
	caption      : "<?php echo $this->lang->line('G_CAPTION') ?>",
	multiselect  : true,
	forceFit     : true,
	rownumbers   : true,
	sortable     : true,
	ondblClickRow:function(rowid,iCol, cellcontent,e){
	    var rowsSelected=rowid;
	    dialogo(rowsSelected);
	},
        grouping:true, 
        groupingView : { 
            groupField : ['ano_mes_envio'], 
            groupColumnShow : [false], 
            groupText : ['<b>{0} - {1} Persona(s)</b>'] 
        }
    });

    jQuery("#filtro-<?php echo $this->pre ?>").jqGrid(
        'navGrid',
        '#barra-<?php echo $this->pre ?>',
        {
	    edit:false,
	    add :false,
	    del :false,
	    view:true
        },
        {},
        {},
        {},
        {
	    multipleSearch:true,
	    multipleGroup :true
        }
    ).jqGrid(
        'navButtonAdd',
        "#barra-<?php echo $this->pre ?>",
        {
            caption:"",
            buttonicon:"ui-icon-trash",
            onClickButton: function(){
		var rowsSelected = $("table#filtro-<?php echo $this->pre ?>").getGridParam('selarrrow');
		$("body").append('<div id="dialog-confirm">Esta Seguro de Eliminar los items seleccionados</div>');
		data='ids='+rowsSelected;
		$( "#dialog-confirm" ).dialog({
		    resizable: false,
		    modal: true,
		    width:500,
		    buttons: {
			"Eliminar todos los items": function() {
			    hace_post('<?php echo $this->url."eliminar" ?>',data,true);
			    jQuery("#filtro-<?php echo $this->pre ?>").trigger("reloadGrid");
			    $( this ).dialog( "close" );
			},
			Cancel: function() {
			    $( this ).dialog( "close" );
			}
		    }
		});
            },
            position:"first"
        }
    ).jqGrid(
        'navButtonAdd',
        "#barra-<?php echo $this->pre ?>",
        {
            caption:"",
            buttonicon:"ui-icon-pencil",
            onClickButton: function(){
		var rowsSelected = $("table#filtro-<?php echo $this->pre ?>").getGridParam('selarrrow');
		dialogo(rowsSelected);
            },
            position:"first"
        }
    ).jqGrid(
        'navButtonAdd',
        "#barra-<?php echo $this->pre ?>",
        {
            caption:"",
            buttonicon:"ui-icon-plus",
            onClickButton: function(){
		var rowsSelected='_';
                dialogo(rowsSelected);
            },
            position:"first"
        }
    ).jqGrid(
        'sortableRows'
    ).jqGrid(
        'gridResize'
    );


    $('button[id="enviar"]').live('click',function(){
	enviar =$(this);
	formid =enviar.offsetParent().attr("id");
	campos =['id','ano-envio','mes-envio','empresa_id','dni','apellido1','apellido2','nombre','nacimiento','sexo','nivelformativo','discapacidad','inmigrante','colocado','fcolocado','tcontrato','cifnif','empresa','nueva','insercion','perceptora'];
	data   =prepara_post(enviar,campos,formid);
	resp   =hace_post('<?php echo site_url($this->url."guardar") ?>',data,false);
	jQuery("#filtro-<?php echo $this->pre ?>").trigger("reloadGrid");
	muestra_msj(formid,campos,resp);
    });


    /*
     * TOTALES
     * */
    function fn_editvalor(response, postdata){
	window.console.log(response);
	window.console.log(postdata);
	return false;
    }

    var lastsel='';
    jQuery("#filtro-<?php echo $this->pret ?>").jqGrid({
	url:'<?php echo site_url($this->url.'gridtotal') ?>',
	datatype: "json",
        colNames:[
	    "<?php echo $this->lang->line('G_ID')                        ?>",
	    "<?php echo $this->lang->line('GT_PERS')                     ?>",
	    "<?php echo $this->lang->line('GT_NUEVAS')                   ?>",
	    "<?php echo $this->lang->line('GT_PERS_PERCEPTORAS')         ?>",
	    "<?php echo $this->lang->line('GT_PERS_INSERCION')           ?>",
	    "<?php echo $this->lang->line('GT_OFERTAS')                  ?>",
	    "<?php echo $this->lang->line('GT_OFERTAS_ENVIADAS')         ?>",
	    "<?php echo $this->lang->line('GT_OFERTAS_CUBIERTAS')        ?>",
	    "<?php echo $this->lang->line('GT_PUE')                      ?>",
	    "<?php echo $this->lang->line('GT_PUE_CUB')                      ?>",
	    "<?php echo $this->lang->line('GT_CON')                      ?>",
	    "<?php echo $this->lang->line('GT_CON_INDEFINIDOS')          ?>",
	    "<?php echo $this->lang->line('GT_COLOCADAS')                ?>",
	    "<?php echo $this->lang->line('G_ANO_MES_ENVIO')             ?>"
        ],
	colModel:[
	    {
		name          :'id'                 ,
		index         :'id'                 ,
                hidden        :true                 ,
		key           :true                 ,
	    },
            {
		name          :'personas'           ,
		index         :'personas'           ,
		width         : 70                  ,
                editable      : true
	    },
            {
		name          :'nuevas'             ,
		index         :'nuevas'             ,
		width         : 70                  ,
                editable      : true
	    },
            {
		name          :'perceptoras'        ,
		index         :'perceptoras'        ,
		width         : 70                  ,
                editable      : true
	    },
            {
		name          :'insercion'          ,
		index         :'insercion'          ,
		width         : 70                  ,
                editable      : true
	    },
            {
		name          :'ofertas'            ,
		index         :'ofertas'            ,
		width         : 70                  ,
                editable      : true
	    },
            {
		name          :'ofertas_enviadas'   ,
		index         :'ofertas_enviadas'   ,
		width         : 70                  ,
                editable      : true
	    },
            {
		name          :'ofertas_cubiertas'  ,
		index         :'ofertas_cubiertas'  ,
		width         : 70                  ,
                editable      : true
	    },
            {
		name          :'puestos'            ,
		index         :'puestos'            ,
		width         : 70                  ,
                editable      : true
	    },
            {
		name          :'puestos_cubiertos'  ,
		index         :'puestos_cubiertos'  ,
		width         : 70                  ,
                editable      : true
	    },
            {
		name          :'contratos'          ,
		index         :'contratos'          ,
		width         : 70                  ,
                editable      : true
	    },
            {
		name          :'contratos_indefinidos' ,
		index         :'contratos_indefinidos' ,
		width         : 70                     ,
                editable      : true
	    },
            {
		name          :'colocadas'          ,
		index         :'colocadas'          ,
		width         : 70                  ,
                editable      : true
	    },
            {
		name          :'ano_mes_envio'      ,
		index         :'ano_mes_envio'         
	    }
	],
	rowNum       : 12,
	width        : 900,
	height       : "auto",
	sortname     : 'nombre',
	viewrecords  : false,
	pager        : '#barra-<?php echo $this->pret ?>',
	hiddengrid   :false,
	sortorder    : "asc",
	caption      : "<?php echo $this->lang->line('GT_CAPTION') ?>",
	forceFit     : true,
	rownumbers   : true,
	sortable     : true,
	pgbuttons    :false,
	pginput      :false,
	onHeaderClick:function(gridstate){
	    if(gridstate=='visible')
		jQuery("#filtro-<?php echo $this->pret ?>").trigger("reloadGrid");
	},
	onSelectRow: function(id){
	    if(id && id!==lastsel){
		jQuery("#filtro-<?php echo $this->pret ?>").jqGrid('restoreRow',lastsel);
		jQuery("#filtro-<?php echo $this->pret ?>").jqGrid('editRow',id,
				                                   {
					                               keys    :true,
					                               url     : '<?php echo $this->url."guardartotal" ?>',
					                               successfunc:function(response){
						                           resp=jQuery.parseJSON(response.responseText);
						                           l   =resp.error.length;
						                           if(l>0){
							                       $("body").append('<div id="error">'+resp.error+'</div>');
							                       $('#error').dialog({modal: true});
							                       return false;
						                           }else{
							                       return true;
						                           }
					                               }
				                                   });
		lastsel=id;
	    }
	},
        grouping:true, 
        groupingView : { 
            groupField : ['ano_mes_envio'], 
            groupColumnShow : [false], 
            groupText : ['<b>Datos Agregados del {0}</b>'] 
        }
    });

    jQuery("#filtro-<?php echo $this->pret ?>").jqGrid(
        'navGrid',
        '#barra-<?php echo $this->pret ?>',
        {
	    edit:false,
	    add :false,
	    del :false,
	    view:false,
	    search:false,
        },
        {},
        {},
        {},
        {
	    multipleSearch:false,
	    multipleGroup :false,
	    showQuery     :false
        }
    );
})
